package com.esiag.isidis.fi.pdsteam.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.esiag.isidis.fi.pdsteam.entity.Info;
import com.esiag.isidis.fi.pdsteam.entity.ParsedMessage;
import com.esiag.isidis.fi.pdsteam.entity.RawByteObject;
import com.esiag.isidis.fi.pdsteam.entity.TramConfig;

public class DataParser implements IParser {

	public ParsedMessage parse(RawByteObject rawByteObject,
			String pathFileConfig) {

		File xmlFile = new File(pathFileConfig);
		// lecteur du fichier xml et exctaction des infos sur la trame
		TramConfig tramConfig = extractConfig(xmlFile);

		// Construction du message
		MessageConstructor messageConstructor = new MessageConstructor();
		ParsedMessage message = messageConstructor.construct(rawByteObject,
				tramConfig);

		return message;
	}

	public TramConfig extractConfig(File xmlFile) {

		TramConfig tramConfig = new TramConfig();
		SAXBuilder builder = new SAXBuilder();
		try {
			Document document = (Document) builder.build(xmlFile);
			Element rootNode = document.getRootElement();

			List<?> list = rootNode.getChildren("info");

			for (int i = 0; i < list.size(); i++) {
				Info tempInfo = new Info();
				Element node = (Element) list.get(i);
				tempInfo.setOrdre(Integer.parseInt(node.getChildText("ordre")));
				tempInfo.setLongueur(Integer.parseInt(node
						.getChildText("longueur")));
				tempInfo.setLibelle(node.getChildText("libelle"));
				tempInfo.setType(node.getChildText("type"));
				tramConfig.getListInfo().add(tempInfo);
			}
		} catch (IOException io) {
			System.out.println("le chemin du fichier et introuvable");
		} catch (JDOMException jdomex) {
			System.out.println(jdomex.getMessage());
		}

		return tramConfig;
	}

}
